#include "SpriteApp.h"

SpriteApp::SpriteApp()
{
}

SpriteApp::SpriteApp(HINSTANCE hInstance, std::string winCaption)
	: D3DApp(hInstance, winCaption, D3DDEVTYPE_HAL, D3DCREATE_HARDWARE_VERTEXPROCESSING)
	, mCenter(128.0f, 128.0f, 0.0f)
	, mPosition(0.0f, 0.0f, 0.0f)
{
	D3DXCreateSprite(gD3DDevice, &mSpriteBatch);
	HR(D3DXCreateTextureFromFile(gD3DDevice, "Acorn256.png", &mTexture));

	OnResetDevice();
}

SpriteApp::~SpriteApp()
{
	ReleaseCOM(mTexture);
	ReleaseCOM(mSpriteBatch);
}

void SpriteApp::OnLostDevice()
{
	mSpriteBatch->OnLostDevice();
}

void SpriteApp::OnResetDevice()
{
	mSpriteBatch->OnResetDevice();

	D3DXMATRIX view;
	D3DXMATRIX orth;
	D3DXVECTOR3 pos(0.0f, 0.0f, -100.0f);
	D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
	D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);

	D3DXMatrixLookAtLH(&view, &pos, &target, &up);
	D3DXMatrixOrthoLH(&orth, (float)mD3Dpp.BackBufferWidth,
		(float)mD3Dpp.BackBufferHeight, 1.0f, 5000.0f);

	HR(gD3DDevice->SetRenderState(D3DRS_LIGHTING, false));
	HR(gD3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE));

	// pour le Alpha
	HR(gD3DDevice->SetRenderState(D3DRS_ALPHAREF, 10));
	HR(gD3DDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER));
	HR(gD3DDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE));
	
	// alpha blend
	HR(gD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE));
	HR(gD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1));
	HR(gD3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA));
	HR(gD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA));

	// Fixed pipeline
	HR(gD3DDevice->SetTransform(D3DTS_VIEW, &view));
	HR(gD3DDevice->SetTransform(D3DTS_PROJECTION, &orth));
}

void SpriteApp::Update(float dt)
{
	
}

void SpriteApp::Draw()
{
	HR(gD3DDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0));

	RECT fontRect;
	::GetClientRect(GetMainWindow(), &fontRect);

	D3DXMATRIX S, IS;
	D3DXMatrixScaling(&S, 1.0f, -1.0f, 1.0f);
	D3DXMatrixInverse(&IS, 0, &S);

	HR(gD3DDevice->BeginScene());
	{
		HR(mSpriteBatch->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_OBJECTSPACE | D3DXSPRITE_DONOTMODIFY_RENDERSTATE));
		{
			HR(mSpriteBatch->SetTransform(&S));
			HR(mSpriteBatch->Draw(mTexture, 0, &mCenter, &mPosition, D3DCOLOR_XRGB(255, 255, 255)));
			mSpriteBatch->Flush();
		}
		HR(mSpriteBatch->End());

		HR(mSpriteBatch->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_OBJECTSPACE | D3DXSPRITE_DONOTMODIFY_RENDERSTATE));
		{
			//HR(mSpriteBatch->SetTransform(&IS));
			//HR(mSpriteBatch->Draw(mTexture, 0, &mCenter, &D3DXVECTOR3(20.0f, 0.0f, 0.0f), D3DCOLOR_XRGB(255, 255, 255)));
		}
		HR(mSpriteBatch->End());
	}
	HR(gD3DDevice->EndScene());

	HR(gD3DDevice->Present(0, 0, 0, 0));
}
